﻿using System;
using System.Linq;
using BingoClientModel;
using BingoCommonConfig.Log4netConfig;
using BingoServerCommon.Common;
using HPSocketCS;

namespace BingoHallServerConsole
{
	public partial class BingoTcpPackServer
	{
		public static TcpPackServer Server = new TcpPackServer();

		public string ip { get; set; }
		public ushort port { get; set; }

		public BingoTcpPackServer(string ip, ushort port)
		{
			this.ip = ip;
			this.port = port;
		}

		public void Start()
		{
			try
			{
				#region 设置服务器事件

				//准备监听了事件
				Server.OnPrepareListen += new TcpServerEvent.OnPrepareListenEventHandler(OnPrepareListen);
				//握手成功事件
				Server.OnHandShake += new TcpServerEvent.OnHandShakeEventHandler(OnHandShake);
				//连接到达事件
				Server.OnAccept += new TcpServerEvent.OnAcceptEventHandler(OnAccept);
				//数据包发送事件
				Server.OnSend += new TcpServerEvent.OnSendEventHandler(OnSend);
				//数据到达事件
				Server.OnReceive += new TcpServerEvent.OnReceiveEventHandler(OnReceive);
				//数据到达事件(指针数据)
				//Server.OnPointerDataReceive += new TcpServerEvent.OnPointerDataReceiveEventHandler(OnPointerDataReceive);
				//连接关闭事件
				Server.OnClose += new TcpServerEvent.OnCloseEventHandler(OnClose);
				//服务器关闭事件
				Server.OnShutdown += new TcpServerEvent.OnShutdownEventHandler(OnShutdown);

				#endregion

				// 设置包头标识,与对端设置保证一致性
				Server.PackHeaderFlag = 0xff;
				// 设置最大封包大小
				Server.MaxPackSize = 0x256;  //byte  

				Server.IpAddress = ip;
				Server.Port = port;
				// 启动服务
				Server.Start();

			}
			catch (Exception e)
			{
				Console.WriteLine("BingoTcpPackServer.Start() 异常");
				LogHelper.WriteFatal("BingoTcpPackServer.Start", e);
			}
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="msg"></param>
		public static void BroadCast(string msg)
		{
			//广播
			var id = Server.GetAllConnectionIDs().ToList();


			//room发
			//var room = RoomManager.roomList.FirstOrDefault();
			//var connId = room.observedList.Select(t => t.connId).ToList();
			//var connId2 = room.observerList.Select(t => t.connId).ToList();
			//var id = connId.Concat(connId2);



			for (int i = 0; i < id.Count(); i++)
			{
				string aa = Guid.NewGuid().ToString();
				Session se = Server.GetExtra<Session>(id[i]);
				//Server.Send(id[i], aa);
				Package pkg = new Package(EnumPackCommand.SC_BroadCastTest);
				pkg.Write("BroadCastTest" + aa);
				//se.Send(pkg);
			}

		}


	}

}
